package edu.gatech.arktos;

import java.net.URL;

import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;
import com.google.gdata.data.spreadsheet.WorksheetEntry;


public class Session {

	private SpreadsheetService service;
	private URL feedurl;
	private SpreadsheetFeed feed;

	public Session(){

	}

	/**
	 * Make call to Google servers and verifies if username and passwords are correct
	 * @param user
	 * @param pw
	 * @return 0 if correct, 1 if not
	 */
	public int login(String user, String pw)
	{
		service = new SpreadsheetService("");
		try
		{
			service.setUserCredentials(user,pw);
			feedurl = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
			feed = service.getFeed(feedurl, SpreadsheetFeed.class);
			return 0;
		}
		catch(Exception e)
		{
			System.out.println("Exception: " + e.getMessage());
			return 1;
		}

		// Send to server: user, pw
		// listen for response
	}

	/**
	 * Logs the user out
	 * @return 0 if successful
	 */
	public int logout(){
		return 1;
	}

	/**
	 * Checks with google docs and returns the excel file by the name we passed in.
	 * @param dbName - database name
	 * @return db - This is the excel file.
	 */
	public GradesDB getDBByName(String dbName){
		GradesDB db = null;
		String sheetTitle;
		
		for(int i = 0; i < feed.getEntries().size(); i++){
			/* Gets the name of the all the excel sheets on your google doc by index */
			sheetTitle = feed.getEntries().get(i).getTitle().getPlainText(); 
			if(sheetTitle.equals(dbName)){
				SpreadsheetEntry anExcelFile = feed.getEntries().get(i);
				db = new GradesDB(anExcelFile);
				return db;
			}
			
		}

		return db;
	}
}
